<template>
  {{ title }}
  <el-form
    label-position="top"
    label-width="100px"
    :model="formDataWrapper.data"
    style="max-width: 800px"
  >
    <el-form-item label="菜品分类:">
      <el-select v-model="type" class="m-2" placeholder="Select" size="large">
        <el-option
          v-for="item in categoryListData.res.records"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="菜品名称:">
      <el-input v-model="formDataWrapper.data.name" />
    </el-form-item>
    <el-form-item label="菜品价格:">
      <el-input v-model="formDataWrapper.data.price" />
    </el-form-item>

    <el-form-item label="口味做法配置:">
      <flavor-setting-component
        ref="flavorSetting"
        :outerData="containerList"
      ></flavor-setting-component>
      <!-- <flavor-setting/> -->
    </el-form-item>

    <el-form-item label="菜品图片:">
      <el-upload
        class="avatar-uploader"
        action="/api/common/upload"
        :show-file-list="false"
        :on-success="methods.handleAvatarSuccess"
        :before-upload="methods.beforeAvatarUpload"
      >
        <img
          v-if="imageUrl"
          :src="methods.getImageUrl(imageUrl)"
          class="avatar"
        />
        <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
      </el-upload>
    </el-form-item>

    <el-form-item label="菜品描述:">
      <el-input
        :rows="3"
        type="textarea"
        v-model="formDataWrapper.data.description"
      />
    </el-form-item>
  </el-form>

  <el-button @click="methods.send(true)">取消</el-button>

  <el-button
    type="primary"
    v-if="isEditMode == true"
    @click="methods.requestModifyData"
  >
    修改菜品
  </el-button>
  <el-button
    type="primary"
    v-if="isEditMode == true"
    @click="methods.getFlavorData"
  >
    保存并继续修改菜品
  </el-button>

  <el-button
    type="primary"
    v-if="isEditMode == false"
    @click="methods.requestData"
  >
    保存菜品
  </el-button>
  <el-button
    type="primary"
    v-if="isEditMode == false"
    @click="methods.getFlavorData"
  >
    保存并继续添加菜品
  </el-button>
</template>
<script lang="ts">
import {
  categoryAdd,
  categoryList,
  categoryListByType,
} from "@/api/CategoryManage";
import { dishAdd, dishById, dishUpdate } from "@/api/DishManage";
import {
  CategoryAddReqForm,
  CategoryAddReqFormWrapper,
  CategoryListByTypeReqForm,
  CategoryListResForm,
  CategoryListResListenObject,
  DishAddReqForm,
  DishAddReqFormWrapper,
  DishSingleReqForm,
} from "@/entity/entityDefine";
import { flavorData, rowData } from "@/entity/inlineEntityDefines";
import { defineComponent, nextTick, reactive, ref } from "vue";
import { ElMessage, UploadProps } from "element-plus";
import FlavorSetting from "./FlavorSetting.vue";
import FlavorSettingComponent from "./FlavorSettingComponent.vue";

export default defineComponent({
  emits: ['fatherFun'], // 避免vue3 emit 报错
  components: { FlavorSettingComponent },
  name: "CategoryEdit",
  props: {
    msg: String,
    title: String,
    dishId: String,
    editMode: Boolean,
  },
  mounted() {
    console.log("mounted");
    this.methods.requestDishCategoryData();
    this.methods.setDishId(this.dishId ?? "");
    this.methods.setEditMode(this.editMode);
  },

  setup(props, { emit }) {
    const isEditMode = ref(false);
    const dishId = ref("");
    let containerList = ref([
      {
        vid: "1",
        name: "自定义",
        value: ["烧烤", "变态辣"],
      },
      {
        vid: "1",
        name: "自定义",
        value: ["烧烤", "变态辣"],
      },
    ]);

    const flavorSetting = ref();
    const imageUrl = ref("");
    const refreshSelectFlag = ref(false);
    const type = ref("");
    const options = ref([
      {
        name: "123",
        id: "1",
      },
    ]);
    const data: CategoryAddReqForm = {
      name: "",
      type: 0,
      sort: 0,
    };

    let respData: CategoryListResForm = reactive({
      records: [
        {
          id: "",
          type: 1,
          name: "",
          sort: 1,
          createTime: "",
          updateTime: "",
          createUser: "",
          updateUser: "",
        },
      ],
      total: 0,
      size: 0,
      current: 0,
      pages: 0,
      searchCount: 0,
    });
    let categoryListData: CategoryListResListenObject = reactive({
      res: respData,
    });

    let params: CategoryListByTypeReqForm = {
      type: 1,
    };

    const formData: DishAddReqForm = {
      id:"",
      name: "",
      categoryId: "",
      price: 0,
      code: "",
      image: "",
      description: "",
      status: 1,
      sort: 1,
      flavors: [],
    };

    const formDataWrapper: DishAddReqFormWrapper = reactive({
      data: formData,
    });

    const vidGen = ref(0);

    const methods = {
      setEditMode(state: boolean) {
        isEditMode.value = state;
        if (!state) {
          // 添加 模式 重置
          //
          formDataWrapper.data = {
            id:"",
            name: "",
            categoryId: "",
            price: 0,
            code: "",
            image: "",
            description: "",
            status: 1,
            sort: 1,
            flavors: [],
          };
          imageUrl.value = "";
          nextTick(() => {
            containerList.value = [];
            flavorSetting.value.methods.setData([]);
          });

        } else {
          // 编辑模式
        }
      },

      setDishId(inputDishId: string) {
        //
        dishId.value = inputDishId;
        if (inputDishId !== "") {
          // request details
          console.log("编辑状态 -- 获取信息 " + inputDishId);
          methods.requestSingleDishData();
        }
      },

      getVid() {
        vidGen.value = vidGen.value + 1;
        console.log("gen:" + vidGen.value);
        return "vid_" + vidGen.value;
      },

      getFlavorData() {
        let list: flavorData[] = [];
        list = flavorSetting.value.methods.getData();
        return list;
      },

      send(result: boolean) {
        emit("fatherFun", result); // 第一个参数是子组件派发的函数名(子传父是通过函数事件派发)
      },

      handleAvatarSuccess(res: any, file: any) {
        console.log(res.data);
        // imageUrl.value = methods.getImageUrl(res.data)
        imageUrl.value = res.data;
      },

      beforeAvatarUpload(rawFile: { type: string; size: number }) {
        if (rawFile.type !== "image/jpeg") {
          ElMessage.error("Avatar picture must be JPG format!");
          return false;
        } else if (rawFile.size / 1024 / 1024 > 2) {
          ElMessage.error("Avatar picture size can not exceed 2MB!");
          return false;
        }
        return true;
      },
      getImageUrl(url: string) {
        return "http://localhost:8082/common/download?fileName=" + url;
      },

      async requestData() {
        formDataWrapper.data.categoryId = type.value;
        formDataWrapper.data.image = imageUrl.value;
        formDataWrapper.data.flavors = methods.getFlavorData();

        const { code, msg, data } = await dishAdd(formDataWrapper.data);

        if (code == 200) {
          ElMessage.success("添加成功");
          // 清空数据
          formDataWrapper.data = {
            id:"",
            name: "",
            categoryId: "",
            price: 1,
            code: "",
            image: "",
            description: "",
            status: 1,
            sort: 1,
            flavors: [],
          };

          methods.send(true);
        } else {
          methods.send(false);
          // 网络层已提示信息
          // console.log(msg);
        }
      },

      async requestModifyData() {
        formDataWrapper.data.categoryId = type.value;
        formDataWrapper.data.image = imageUrl.value;
        formDataWrapper.data.flavors = methods.getFlavorData();

        const { code, msg, data } = await dishUpdate(formDataWrapper.data);

        if (code == 200) {
          ElMessage.success("修改成功");
          // 清空数据
          formDataWrapper.data = {
            id: "",
            name: "",
            categoryId: "",
            price: 0,
            code: "",
            image: "",
            description: "",
            status: 1,
            sort: 1,
            flavors: [],
          };
          type.value = "";
          imageUrl.value = "";
          nextTick(() => {
            containerList.value = [];
            flavorSetting.value.methods.setData([]);
          });
          

          methods.send(true);
        } else {
          methods.send(false);
          // 网络层已提示信息
          // console.log(msg);
        }
      },

      async requestSingleDishData() {
        const req: DishSingleReqForm = {
          id: dishId.value,
        };

        const { code, msg, data } = await dishById(req);

        if (code == 200) {
          let singleData = data!;
          formDataWrapper.data.id = singleData.id;
          formDataWrapper.data.categoryId = singleData.categoryId;
          formDataWrapper.data.name = singleData.name;
          formDataWrapper.data.price = singleData.price;
          formDataWrapper.data.image = singleData.image;
          formDataWrapper.data.description = singleData.description;
          imageUrl.value = singleData.image;
          type.value = singleData.categoryId;
          let tempList: { vid: string; name: string; value: string[] }[] = [];
          singleData.flavors.forEach((item, index) => {
            //
            let list = item.value.split(",");
            tempList.push({
              vid: methods.getVid(),
              name: item.name,
              value: list,
            });
          });

          nextTick(() => {
            containerList.value = tempList;
            flavorSetting.value.methods.setData(tempList);
          });

          console.log("追加数据" + containerList.value.length);
        } else {
          methods.send(false);
          // 网络层已提示信息
          // console.log(msg);
        }
      },

      refreshT() {
        methods.requestDishCategoryData();
      },

      forceRerender() {
        refreshSelectFlag.value = false;
        nextTick(() => {
          refreshSelectFlag.value = true;
        });
      },

      async requestDishCategoryData() {
        params.type = 1;

        const { code, msg, data } = await categoryListByType(params);

        if (code == 200) {
          //
          let res = data!;
          categoryListData.res = res;
        } else {
          // 网络层已提示信息
          // console.log(msg);
        }
      },
    };

    return {
      formDataWrapper,
      methods,
      type,
      categoryListData,
      options,
      refreshSelectFlag,
      imageUrl,
      flavorSetting,
      containerList,
      isEditMode,
    };
  },
});
</script>

function emit(arg0: string, str: any) { throw new Error("Function not
implemented."); }

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
